package com.imooc.town.controller;

import com.imooc.town.dataobject.ProductCategory;
import com.imooc.town.dataobject.ProductInfo;
import com.imooc.town.service.CategoryService;
import com.imooc.town.service.ProductService;
import com.imooc.town.utils.ResultVOUtil;
import com.imooc.town.vo.ProductInfoVo;
import com.imooc.town.vo.ProductVo;
import com.imooc.town.vo.ResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

/**
 * Created by 10077 on 2018/3/21.
 * desc:
 */

@RequestMapping("/buyer/product")
@RestController
public class BuyerProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private CategoryService categoryService;


    @GetMapping("/list")
    public ResultVo list(){
//        1、查询所有上架的商品
        List<ProductInfo> productInfoList = productService.findUpAll();
//        2、查询类目，一次性查询
//      精简方法（java8，lambda）
        List<Integer> categoryTypeList = productInfoList.stream().map(e->e.getCategoryType()).collect(Collectors.toList());
        List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(categoryTypeList);
//        3、数据拼装
        List<ProductVo> productVoList = new ArrayList<>();
        for (ProductCategory category : productCategoryList){
            ProductVo productVo = new ProductVo();
            productVo.setCategoryName(category.getCategoryName());
            productVo.setCategoryType(category.getCategoryType());
            List<ProductInfoVo> productInfoVoList = new ArrayList<>();
            for(ProductInfo productInfo : productInfoList){
                if (productInfo.getCategoryType().equals(category.getCategoryType())){
                    ProductInfoVo productInfoVo = new ProductInfoVo();
                    BeanUtils.copyProperties(productInfo,productInfoVo);
                    productInfoVoList.add(productInfoVo);
                }
            }
            productVo.setProductInfoVoList(productInfoVoList);
            productVoList.add(productVo);
        }
        return ResultVOUtil.success(productVoList);
    }

}
